package com.tanhua.sso.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.RSA;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * 初始化RSA，读取RSA的密钥文件
 */
@Service
@Data
public class RSAService {

    private String privateKey;
    private String publicKey;

    @Value("${tanhua.rsa.dir}")
    private String rsaDir;

    /**
     * 完成公钥、私钥的读取操作
     */
    @PostConstruct
    public void init() {
        //私钥的文件路径，通过File.separator解决跨平台的目录分隔符的问题
        String privateKeyFile = rsaDir + File.separator + "rsa";
        String publicKeyFile = rsaDir + File.separator + "rsa.pub";

        if (FileUtil.exist(privateKeyFile)) {
            //读取
            this.privateKey = FileUtil.readString(privateKeyFile, CharsetUtil.CHARSET_UTF_8);
        }

        if (FileUtil.exist(publicKeyFile)) {
            //读取
            this.publicKey = FileUtil.readString(publicKeyFile, CharsetUtil.CHARSET_UTF_8);
        }

        //如果公钥和私钥都不存在，就需要创建公钥和私钥
        if (!StrUtil.isAllEmpty(privateKey, publicKey)) {
            return;
        }
        //生成新的公钥和私钥
        RSA rsa = new RSA();
        //将公钥和私钥写入到文件
        FileUtil.writeString(rsa.getPrivateKeyBase64(), privateKeyFile, CharsetUtil.CHARSET_UTF_8);
        FileUtil.writeString(rsa.getPublicKeyBase64(), publicKeyFile, CharsetUtil.CHARSET_UTF_8);

        //第一次生成时，赋值给变量
        this.privateKey = rsa.getPrivateKeyBase64();
        this.publicKey = rsa.getPublicKeyBase64();

    }
}
